package com.example.administrator.liveapp.fragment;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.Resource;
import com.example.administrator.liveapp.R;
import com.example.administrator.liveapp.Xutils3.MyCallBack;
import com.example.administrator.liveapp.Xutils3.XUtils;
import com.example.administrator.liveapp.activity.MallDetailsPage;
import com.example.administrator.liveapp.adapter.LiveFragmentAdapter;
import com.example.administrator.liveapp.base.BaseFragment;
import com.example.administrator.liveapp.base.BaseRVAdapter;
import com.example.administrator.liveapp.base.BaseViewHolder;
import com.example.administrator.liveapp.bean.LiveListBean;
import com.example.administrator.liveapp.bean.MallListBean;
import com.example.administrator.liveapp.bean.ShoppingListBean;
import com.example.administrator.liveapp.utils.AppUrl;
import com.example.administrator.liveapp.utils.LogU;
import com.example.administrator.liveapp.view.FullyGridLayoutManager;
import com.example.administrator.liveapp.view.FullyLinearLayoutManager;
import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 商城列表Fragment
 */

public class MallFragment extends BaseFragment implements View.OnClickListener{
    private View view;
    private RecyclerView mall_tab1_Recycle,column;
    private ImageView mall_image;
    ShoppingListBean ListBean;
    MallListBean bean;
    private String consumerId;//用户id
    private View loadView;//loding页面（加载页）
    private TextView item_mall_null;
    /**
     * 下拉刷新
     */
    private RefreshLayout mRefreshLayout;
    private static boolean isFirstEnter = true;

    @Override
    protected View initView() {
        view = View.inflate(getActivity(),R.layout.mallfragment_layout,null);
        loadView = view.findViewById(R.id.loadView);
        mall_tab1_Recycle = (RecyclerView) view.findViewById(R.id.mall_tab1_Recycle);
        column = (RecyclerView) view.findViewById(R.id.column);
        mall_image = (ImageView) view.findViewById(R.id.mall_image);
        item_mall_null = (TextView) view.findViewById(R.id.item_mall_null);
        mall_image.setOnClickListener(this);
        mall_image.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, getActivity().getWindowManager().getDefaultDisplay().getWidth() / 1 * 1));
        /**
         * 下拉刷新
         */
        mRefreshLayout = (RefreshLayout)view.findViewById(R.id.refreshLayout);
        setThemeColor(R.color.colorPrimary);
        if (isFirstEnter) {
            initData();
            isFirstEnter = false;
//            mRefreshLayout.autoRefresh();//第一次进入触发自动刷新，演示效果
        }
        return view;
    }

    private void setThemeColor(int colorPrimary) {
        mRefreshLayout.setPrimaryColorsId(colorPrimary, android.R.color.holo_blue_dark);
    }

    public List<Boolean> isClicks;//控件是否被点击,默认为false，如果被点击，改变值，控件根据值改变自身颜色

//    @Override
//    public void onPause() {
//        super.onPause();
//        initData();
//    }

    @Override
    protected void initData() {
        super.initData();
        String url = AppUrl.URL+AppUrl.MallColumnURL;
        XUtils.Get(url,null,new MyCallBack<String>(){
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Gson gson = new Gson();
                bean = gson.fromJson(result, MallListBean.class);
                Glide.with(getContext())
                        .load(AppUrl.URL+bean.getBookImg().getBookbannerimg())
                        .into(mall_image);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
            }

            @Override
            public void onFinished() {
                super.onFinished();
                listener();
                setData();
                loadView.setVisibility(View.GONE);
                isClicks = new ArrayList<>();
                for(int i = 0;i<bean.getColumn().size();i++){
                    if(i==0){
                        isClicks.add(true);
                    }
                    isClicks.add(false);
                }
                String url = AppUrl.URL+ AppUrl.ShoppingListURL;
                Map<String,String> map = new HashMap();
                map.put("column","全部");
                XUtils.Get(url,map,new MyCallBack<String>(){
                    @Override
                    public void onSuccess(String result) {
                        super.onSuccess(result);
                        Gson gson = new Gson();
                        ListBean = gson.fromJson(result, ShoppingListBean.class);
                        mallRecyclerView();
                    }

                    @Override
                    public void onError(Throwable ex, boolean isOnCallback) {
                        super.onError(ex, isOnCallback);
                        Toast.makeText(mContext, ex.getMessage()+"", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onFinished() {
                        super.onFinished();
                    }
                });
            }
        });

    }

    public void setData() {
        FullyLinearLayoutManager fullyLinearLayoutManager = new FullyLinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false);
        fullyLinearLayoutManager.setScrollEnabled(false);
        column.setLayoutManager(fullyLinearLayoutManager);
        column.setAdapter(new BaseRVAdapter(mContext, bean.getColumn()) {

            @Override
            public int getLayoutId(int viewType) {
                return R.layout.item_action_type;
            }

            @Override
            public void onBind(BaseViewHolder holder, final int position) {
                final TextView text = holder.getTextView(R.id.text);
                text.setText(bean.getColumn().get(position).toString());
                if(isClicks.get(position)){
                    text.setBackgroundResource(R.drawable.b9_circle_main);
                    text.setTextColor(Color.parseColor("#FFFFFF"));
                }else{
                    text.setBackgroundResource(R.drawable.b9_circle_white);
                    text.setTextColor(Color.parseColor("#7FC48D"));
                }

                addItemClickListener(new OnItemClickListener() {
                    @Override
                    public void itemSelect(final int positions) {
                        if (positions == 0) {
                            String url = AppUrl.URL+ AppUrl.ShoppingListURL;
                            Map<String,String> map = new HashMap();
                            map.put("column","全部");
                            XUtils.Get(url,map,new MyCallBack<String>(){
                                @Override
                                public void onSuccess(String result) {
                                    super.onSuccess(result);
                                    String mall="";
                                    Gson gson = new Gson();
                                    try {
                                        JSONObject json = new JSONObject(result);
                                        mall = json.optString("result");
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                    ListBean.getBookList1().clear();
                                    ListBean = gson.fromJson(result, ShoppingListBean.class);
                                    if(mall.equals("false")){//该商品分类中是否有商品，没有商品信息显示该分类没有商品
                                        item_mall_null.setVisibility(View.VISIBLE);
                                        mall_tab1_Recycle.setVisibility(View.GONE);
                                    }else{
                                        item_mall_null.setVisibility(View.GONE);
                                        mall_tab1_Recycle.setVisibility(View.VISIBLE);
                                        mallRecyclerView();
                                    }
                                }

                                @Override
                                public void onError(Throwable ex, boolean isOnCallback) {
                                    super.onError(ex, isOnCallback);
                                    Toast.makeText(mContext, "请检查网络连接", Toast.LENGTH_SHORT).show();
                                }

                                @Override
                                public void onFinished() {
                                    super.onFinished();
                                    for(int i = 0; i <isClicks.size();i++){
                                        isClicks.set(i,false);
                                    }
                                    isClicks.set(positions,true);
                                    notifyDataSetChanged();
                                }
                            });
                            return;
                        }
                        String url = AppUrl.URL+ AppUrl.ShoppingListURL;
                        Map<String,String> map = new HashMap();
                        map.put("column",bean.getColumn().get(positions));
                        Log.e("column====",""+positions);
                        XUtils.Get(url,map,new MyCallBack<String>(){
                            @Override
                            public void onSuccess(String result) {
                                super.onSuccess(result);
                                String mall="";
                                LogU.e("----",result);
                                Gson gson = new Gson();
                                try {
                                    JSONObject json = new JSONObject(result);
                                    mall = json.optString("result");
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                                ListBean.getBookList1().clear();
                                ListBean = gson.fromJson(result, ShoppingListBean.class);
                                if(mall.equals("false")){
                                    item_mall_null.setVisibility(View.VISIBLE);
                                    mall_tab1_Recycle.setVisibility(View.GONE);
                                }else{
                                    item_mall_null.setVisibility(View.GONE);
                                    mall_tab1_Recycle.setVisibility(View.VISIBLE);
                                    mallRecyclerView();
                                }
                            }

                            @Override
                            public void onError(Throwable ex, boolean isOnCallback) {
                                super.onError(ex, isOnCallback);
                                Toast.makeText(mContext, "请检查网络连接", Toast.LENGTH_SHORT).show();
                            }

                            @Override
                            public void onFinished() {
                                super.onFinished();
                                for(int i = 0; i <isClicks.size();i++){
                                    isClicks.set(i,false);
                                }
                                isClicks.set(positions,true);
                                notifyDataSetChanged();
                            }
                        });
                    }
                });
            }

        });

    }

    private void mallRecyclerView() {
        //mall_tab1_Recycle
        FullyGridLayoutManager gridLayoutManager = new FullyGridLayoutManager(mContext,2);
        gridLayoutManager.setScrollEnabled(false);
        mall_tab1_Recycle.setHasFixedSize(true);
        mall_tab1_Recycle.setLayoutManager(gridLayoutManager);
        MallTab_1RecyclerViewAdapter tab1 = new MallTab_1RecyclerViewAdapter(ListBean.getBookList1());
        mall_tab1_Recycle.setAdapter(tab1);
        tab1.setOnItemClickListener(new LiveFragmentAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                Intent intent = new Intent();
                intent.putExtra("bookId", ListBean.getBookList1().get(position).getBookid());
                intent.putExtra("bookPrice",ListBean.getBookList1().get(position).getBookprice());
                intent.putExtra("remainCount",ListBean.getBookList1().get(position).getRemainCount());
                intent.setClass(getContext(), MallDetailsPage.class);
                getActivity().startActivity(intent);
            }
        });
    }

    static class MallTab_1RecyclerViewAdapter extends RecyclerView.Adapter<MallTab_1RecyclerViewAdapter.ViewHolder> implements View.OnClickListener {
        public List<ShoppingListBean.BookList1Bean> listBean;
        public Context context;
        public MallTab_1RecyclerViewAdapter(List<ShoppingListBean.BookList1Bean> listBean) {
            this.listBean = listBean;
        }

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.mall_tab_recycle_item, null);
            ViewHolder viewHolder = new ViewHolder(view);
            //将创建的View注册点击事件
            view.setOnClickListener(this);
            context = parent.getContext();
            return viewHolder;
        }

        @Override
        public void onBindViewHolder(ViewHolder holder, final int position) {
            String url = listBean.get(position).getBookimgurl();
            String ImageUrl = url.substring(0, url.indexOf("|"));
            Glide.with(context)
                    .load(AppUrl.URL + ImageUrl)
                    .into(holder.mall_images);
            holder.mall_name.setText(listBean.get(position).getBooktitle());
            holder.mall_money.setText(listBean.get(position).getBookprice());
            holder.buy_num.setText(listBean.get(position).getSalescount() + "人购买");
            //将position保存在itemView的Tag中，以便点击时进行获取
            holder.itemView.setTag(position);
        }

        @Override
        public int getItemCount() {
            if (listBean != null && !listBean.equals("")) {
                return listBean.size();
            } else {
                return 0;
            }
        }

        public class ViewHolder extends RecyclerView.ViewHolder {
            public ImageView mall_images;
            public TextView mall_name;
            public TextView mall_money;
            public TextView buy_num;

            public ViewHolder(View itemView) {
                super(itemView);
                mall_images = (ImageView) itemView.findViewById(R.id.mall_images);
                mall_name = (TextView) itemView.findViewById(R.id.mall_name);
                mall_money = (TextView) itemView.findViewById(R.id.mall_money);
                buy_num = (TextView) itemView.findViewById(R.id.buy_num);
            }
        }

        @Override
        public void onClick(View v) {
            if (mOnItemClickListener != null) {
                //注意这里使用getTag方法获取position
                mOnItemClickListener.onItemClick(v, (int) v.getTag());
            }
        }

        private LiveFragmentAdapter.OnItemClickListener mOnItemClickListener = null;

        //define interface
        public static interface OnItemClickListener {
            void onItemClick(View view, int position);
        }

        public void setOnItemClickListener(LiveFragmentAdapter.OnItemClickListener listener) {
            this.mOnItemClickListener = listener;
        }
    }

    private void listener() {
        mRefreshLayout.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                //底部加载
            }

            @Override
            public void onRefresh(final RefreshLayout refreshlayout) {
                //下拉刷新
                refreshlayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        initData();
                        refreshlayout.finishRefresh();
                    }
                }, 2000);
            }
        });
    }

    java.text.DecimalFormat df = new java.text.DecimalFormat("0.00");//精确到小数点后两位

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.mall_image:
                Intent intent = new Intent();
                intent.putExtra("bookId", bean.getBookImg().getBookid());
                intent.putExtra("bookPrice",df.format(Double.parseDouble(bean.getBookImg().getBookprice())*Double.parseDouble(bean.getBookImg().getDiscount()))+"");
                intent.putExtra("remainCount",bean.getBookImg().getRemainCount());
                intent.setClass(getContext(), MallDetailsPage.class);
                getActivity().startActivity(intent);
                break;
        }
    }
}
